package com.example.project44

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.RadioGroup
import androidx.activity.ComponentActivity

class EditInfoActivity : ComponentActivity() {
    private lateinit var etName: EditText
    private lateinit var etPhone: EditText
    private lateinit var rgGender: RadioGroup
    private lateinit var btnSave: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit)
        initViews()
        initData()
        setListeners()
    }

    private fun initViews() {
        etName = findViewById(R.id.et_name)
        etPhone = findViewById(R.id.et_phone)
        rgGender = findViewById(R.id.rg_gender)
        btnSave = findViewById(R.id.btn_save)
    }

    private fun initData() {
        val name = intent.getStringExtra("name") ?: ""
        val phone = intent.getStringExtra("phone") ?: ""
        val gender = intent.getStringExtra("gender") ?: "男"

        etName.setText(name)
        etPhone.setText(phone)
        if (gender == "女") {
            rgGender.check(R.id.rb_female)
        } else {
            rgGender.check(R.id.rb_male)
        }
    }

    private fun setListeners() {
        btnSave.setOnClickListener { saveInfo() }
    }

    private fun saveInfo() {
        val name = etName.text.toString().ifEmpty { "未知" }
        val phone = etPhone.text.toString().ifEmpty { "未设置" }
        val gender = if (rgGender.checkedRadioButtonId == R.id.rb_male) "男" else "女"

        val intent = Intent().apply {
            putExtra("name", name)
            putExtra("gender", gender)
            putExtra("phone", phone)
        }
        setResult(RESULT_OK, intent)
        finish()
    }
}